        /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tubes1sister.peerConnection.message;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import tubes1sister.tools.DirectorySearchHelper;

/**
 *
 * @author Muhammad Anis
 */
public class MessageFlow {
    //memiliki lengthprefix
    public int lengthprefix;
    //memiliki messageID
    public int messageID;
    //memiliki payload --> generic ternyata -__-"

    //fungsi2
   /* public String generateMessage(String tipe,int pieceindex,String filename){
        if(tipe.equals("have")){
            return generateHaveMessage();
        } else if(tipe.equals("bitfield")){
            return generateBitfieldMessage();
        } else if(tipe.equals("request")){
            return generateRequestMessage();
        } else if(tipe.equals("piece")){
            return generatePieceMessage();
        } else{
            return generateCancelMessage();
        }
    }*/
    
    public static int tipeMessage(String message){
        String temp = message.substring(0,4);
        if(temp.equals("00054"))
            return 1; // --> message haev
        else if(temp.equals("00015"))
            return 2; // --> message bitfield
        else if(temp.endsWith("00136"))
            return 3; // --> message request
        else
            return 4; // --> byte
    }

    private String generateHaveMessage(int pieceindex) {
        String hasil="";

        hasil+="00054"+pieceindex;

        return hasil;
    }

    public static String generateBitfieldMessage(String filename,String hashvalue,int pieceLength, int indexpiece) throws IOException {
        String hasil = "";
        DirectorySearchHelper dsh = new DirectorySearchHelper(".");
        hasil+="00015";
        try {
            if (dsh.getBitField(filename, hashvalue, pieceLength, indexpiece) != null) {
                hasil+="yes";
            }
            else{
                hasil+="nop";
            }
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(MessageFlow.class.getName()).log(Level.SEVERE, null, ex);
        }

        return hasil;
    }

    public static String generateRequestMessage(int pieceindex) {
        String hasil="";

        hasil+="00136"+pieceindex;
        return hasil;
    }

    private String generatePieceMessage() {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    private String generateCancelMessage() {
        throw new UnsupportedOperationException("Not yet implemented");
    }
    
}
